<template>
  <!--  <el-dialog v-model="dialogTableVisible" title="识别结果" width="800">-->
  <!--    <el-table :data="gridData">-->
  <!--      <el-table-column property="uid" label="用户" width="150" />-->
  <!--      <el-table-column  label="识别结果">识别成功</el-table-column>-->
  <!--      &lt;!&ndash;      <el-table-column property="distance" label="差距" width="200" />&ndash;&gt;-->
  <!--    </el-table>-->

  <!--  </el-dialog>-->
  <Popup :visible="dialogTableVisible" :content="popupContent" @close="closePopup"/>

  <div>{{ popupContent }}</div>
  <div v-if="imgSrc" class="img_bg_camera">
    <img id="imagePreview" :src="imgSrc" class="tx_img"/>
  </div>
  <div class="publish">
    <video ref="video" id="video" autoplay class="video"></video>
    <canvas ref="canvas" style="display: none" id="canvasCamera"></canvas>

    <!--    <button @click="OpenCamera">打开摄像头</button>-->
    <!--    <button @click="CloseCamera">关闭摄像头</button>-->
    <!--    <button @click="setImage">拍照</button>-->
    <!--    <button @click="face">识别</button>-->
  </div>
  <!--  <div>-->
  <!--    <input type="file" accept="image/*" @change="handleFileChange">-->

  <!--  </div>-->
</template>

<script setup lang="ts">

import Popup from "./Popup.vue";
import {onMounted, reactive, ref, watch} from "vue";
import {getRecordsById, uploadFaceApi} from "../api/face";

const dialogTableVisible = ref(false)
const gridData = ref([])

const mediaStreamTrack = ref({})
const video_stream = ref('') // 视频stream
const imgSrc = ref('') // 拍照图片
const imgSrcBase64 = ref<any>('') // 拍照图片
const canvas = ref<any>([] as any)
const context = ref<any>('' as any)
const cancas = ref(null)
const photo = ref(null)
const video = ref('' as any)
const popupContent = ref('' as any)
const name = ref('' as any)
const formQuery = reactive({
  ugroup: 'usergroup',
  imagefile: '' as any
})


onMounted(() => {
  // 进入页面 自动调用摄像头
  getCamera();
})

//  base64toBlob,
function handleFileChange(event: any) {

  const file = event.target.files[0];
  if (file) {
    displayPhoto(file);
  }
}


function displayPhoto(dataURL: any) {
  imgSrc.value = dataURL;
  console.log(dataURL)
  formQuery.imagefile = dataURL


  const reader = new FileReader();

  // 定义读取完成时的回调函数
  reader.onload = () => {
    // 设置Base64数据
    imgSrc.value = reader.result as any;
  };

  // 读取文件内容，将结果以 data URL 的形式返回
  reader.readAsDataURL(dataURL);


}

// 调用打开摄像头功能
function getCamera() {
  // 获取 canvas 画布
  canvas.value = document.getElementById('canvasCamera');
  context.value = canvas.value.getContext('2d');
  // // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
  // if (navigator.mediaDevices === undefined) {
  //   navigator.mediaDevices = {};
  // }
  // 正常支持版本
  navigator.mediaDevices
      .getUserMedia({
        video: true,
      })
      .then((stream: any) => {
        // 摄像头开启成功
        mediaStreamTrack.value = typeof stream.stop === 'function' ? stream : stream.getTracks()[0];
        video_stream.value = stream;
        video.value.srcObject = stream;
        video.value.play();
      })
      .catch(err => {
        console.log(err);
      });
}

function face() {
  uploadFace()
}

const faceControl = reactive({
  list: [] as any,
  time: '' as any,
  isSame: false,
  consecutiveSameResults: 0,
  previousResult: null,
})
// faceControl.time = setInterval(function () {
//   takePhoto()
// }, 500);

faceControl.time = setInterval(function () {
  takePhoto(); // Take a photo
  // Assuming `setImage()` updates `faceControl.list` with the result
  const result = faceControl.list[faceControl.list.length - 1]; // Get the latest result
  handleResult(result); // Check for consecutive same results
}, 500);


//去掉定时器的方法


// 拍照 绘制图片
function takePhoto() {
  // 点击canvas画图
  context.value.drawImage(
      video.value,
      10,
      10,
      200,
      100,
  );
  // 获取图片base64链接
  imgSrc.value = canvas.value.toDataURL('image/png');
  let filename = (new Date()).valueOf() + Math.round(Math.random() * 1000) + ".png";
// 将 Base64 字符串转换为 Blob
  const byteCharacters = atob(imgSrc.value.split(',')[1]);
  const byteNumbers = new Array(byteCharacters.length);
  for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
  }
  const byteArray = new Uint8Array(byteNumbers);
  const blob = new Blob([byteArray], {type: 'image/png'}); // 替换为实际的 MIME 类型
  //base64toBlob(imgSrc.value, 'image/png', filename)
  formQuery.imagefile = new File([blob], filename, {type: blob.type});
  return uploadFace()
}

function uploadFace() {
  uploadFaceApi(formQuery).then((response: any) => {
    if (response.state === "success, but not match face") {
      popupContent.value = "识别成功，但是无匹配对象"
      faceControl.list.push(null)
      return null
    } else if (response.error === "not found face") {
      popupContent.value = "未发现人脸"
      faceControl.list.push(null)
      return null
    } else {
      console.log(response)
      //dialogTableVisible.value = true
      // showPopup()
      faceControl.list.push(response[0].uid)
      gridData.value = response
      name.value = response[0].uid
      // popupContent.value = "识别成功:" + name.value
      return response[0].uid
    }

  }).catch((res: any) => {
  }).finally(() => {
  })
}

watch(
    () => faceControl.isSame,
    (value, oldValue) => {

    }, {immediate: true}
)

// Function to handle the result and check for consecutive same results
function handleResult(result: any) {
  if (result === null || result === false) {
    // Reset if result is null or false
    faceControl.previousResult = null;
    faceControl.consecutiveSameResults = 0;
    faceControl.isSame = false;
  } else if (faceControl.previousResult === null) {
    faceControl.previousResult = result;
    faceControl.list=[]
  } else {
    if (result === faceControl.previousResult) {
      faceControl.consecutiveSameResults++;
      if (faceControl.consecutiveSameResults === 5) {
        faceControl.isSame = true;
        getRecordsById(faceControl.list[faceControl.list.length - 1]).then((res: any) => {
          console.log(res.data[0].name)
          popupContent.value = res.data[0].name
        })
      }
    } else {
      faceControl.previousResult = result;
      faceControl.consecutiveSameResults = 1;
      faceControl.isSame = false;
    }
  }
}

function showPopup() {
  dialogTableVisible.value = true;
}

function closePopup() {
  dialogTableVisible.value = false;
}

// 打开摄像头
function OpenCamera() {
  console.log('打开摄像头');
  getCamera();
}

// 关闭摄像头
function CloseCamera() {
  console.log('关闭摄像头');
  video.value.srcObject.getTracks()[0].stop();
}
</script>

<style scoped>
video {
  width: 100%;
  height: 70%;
}


canvas {
  width: 100%;
  height: 300px;
}

button {
  width: 100px;
  height: 40px;
  position: relative;
  bottom: 0;
  left: 0;
  background-color: rgb(22, 204, 195);
}


img {
  width: 300px;
  height: 200px;
}

</style>
